<?php
/**
 * Created by PhpStorm.
 * User: john
 * Date: 2016/11/21
 * Time: 13:01
 */

namespace base;


class CsvFileOut
{
    /**
     * 文件句柄
     * @var null
     */
    private $_file_handle = null;

    /**
     * 构造方法 生成临时文件句柄
     * CsvFileOut constructor.
     */
    public function __construct()
    {
        $this->_file_handle = tmpfile();
    }

    /**
     * 向临时文件写入内容
     * @param $content 文件内容
     */
    public function addFileContent($content)
    {
        fwrite($this->_file_handle, iconv('utf-8', 'gbk', $content));
    }

    /**
     * 输出到文件
     * @param string $name 文件名
     */
    public function outputFile($name = '')
    {
        $this->_setHeader($name);
        fseek($this->_file_handle, 0);
        while (!feof($this->_file_handle)) {
            $line = fgets($this->_file_handle, 524200);
            echo $line;
            ob_flush();
            flush();
        }
    }

    /**
     * 设置头信息
     * @param string $name
     */
    private function _setHeader($name = '')
    {
        if (empty($name)) {
            $name = time();
        }
        header('Pragma:public');
        header('Expires:0');
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header('Content-Type: text/csv');
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition: attachment; filename="' . $name . '.csv"');
        header('Content-Transfer-Encoding: binary');
    }

    /**
     * 关闭文件句柄
     */
    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        if ($this->_file_handle) {
            fclose($this->_file_handle);
        }
    }


}